package com.xishu.util;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class Sha256Util {
    private static Logger logger = LoggerFactory.getLogger(Sha256Util.class);


    public static String sha256(String input, String salt) {
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");

            if (StringUtils.isNotEmpty(salt)) {
                logger.debug("salt is {}", salt);
                messageDigest.update(salt.getBytes());
            }

            byte[] hash = messageDigest.digest(input.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
            logger.debug("input is {},sha256 str is {}", input, encdeStr);
        } catch (Exception e) {
            logger.error("e", e);
        }
        return encdeStr;
    }

    /**
     * HAS 过后的字节数组
     *
     * @param input
     * @return
     */
    public static byte[] sha256ByteArray(String input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

            byte[] hash = messageDigest.digest(input.getBytes("UTF-8"));
            return hash;
        } catch (Exception e) {
            logger.error("e", e);
        }

        return null;
    }

    /**
     * SHA1算法
     *
     * @param input
     * @return
     */
    public static String sha1(String input) {
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-1");

            byte[] hash = messageDigest.digest(input.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
            logger.debug("input is {},sha256 str is {}", input, encdeStr);
        } catch (Exception e) {
            logger.error("e", e);
        }

        return encdeStr;
    }


    public static String sha256(String input) {
        return sha256(input, null);
    }

    /**
     * 产生一个随机的盐值
     *
     * @return
     */
    public static String generateSalt() {
        return RandomUtil.generateString(32);
    }
}
